<script setup lang="ts">
import {ref,onMounted} from 'vue'
import {mobileRules, passwordRules,codeRules} from '@/utiles/rules'
import { showSuccessToast, showFailToast,showToast,type FormInstance} from 'vant'
import { userLogin,sendMobileCode,loginByMobile } from '@/api/user'
import type { Boolean } from '@/types/user'
import { useUserStore } from '@/stores'
import { useRoute, useRouter } from 'vue-router'
// 定义一个响应变量做数据驱动控制是否同意协议
let agree = ref<Boolean>(false)
// 定义一个响应变量做数据驱动控制密码是否可见
let isShowPass = ref<Boolean>(false)
// 准备绑定手机号和密码的变量
let mobile = ref('')
let password = ref('')
// 定义login登录事件函数
const route = useRoute()
const router = useRouter()
const store = useUserStore()
const login = async () => {
    if (!agree.value) return showToast('请勾选我已同意')
    if(isPass.value){
      await userLogin({mobile: mobile.value, password: password.value}).then(res => {
        // 存储用户信息
        store.setUser(res.data)
        // 提示登陆成功
        showSuccessToast('登录成功')
        // 跳转路由
        // 如果有回跳地址就进行回跳，没有跳转到个人中心
        router.push((route.query.returnUrl as string) || '/user')
      }).catch(err => {
        console.log(err)
        // 提示登录失败
        showFailToast('登录失败:'+err.message)
      })
    }else{
      await loginByMobile(mobile.value,code.value).then(
        res => {
          store.setUser(res.data)
           // 提示登陆成功
           showSuccessToast('登录成功')
           // 跳转路由
           // 如果有回跳地址就进行回跳，没有跳转到个人中心
          router.push((route.query.returnUrl as string) || '/user')
        }
      ).catch(
        err => {
          console.log(err);
        // 提示登录失败
          showFailToast('登录失败:'+err.message)
        }
      )
    }
    
}
// 切换页面数据
const isPass = ref<boolean>(true)
// 定义存储验证码数据
const code = ref('')
// 定义倒计时数据
let time = ref(0)
const form = ref<FormInstance>()
// 定义倒计时定时器
let timer: any = null
// 定义发送验证码函数
const send = async () => {
  // 已经倒计时time的值大于0，60s内不能重复发送验证码
  if(time.value > 0) return
  await form.value?.validate('mobile')
  const res = await sendMobileCode(mobile.value,'login')
  console.log(res)
  showSuccessToast('发送成功')
  // 倒计时开始
  time.value = 60
   timer = setInterval(()=>{
    time.value--
    if(time.value<=0) window.clearInterval(timer)
  },1000)
}
// 组件卸载清除定时器防止内存泄漏
onMounted(()=>{
  window.clearInterval(timer)
})
</script>

<template>
  <cp-nav-bar title="登录" right-text="注册" @click-right="$router.push('/register')" :fixed="true"></cp-nav-bar>
  <div class="login">
    <div class="login-head">
      <h3>{{ isPass?'密码登录':'短信登陆' }}</h3>
      <a href="javascript:;" @click="isPass =! isPass">
        <span>{{ isPass?'短信验证码登录':'密码登录' }}</span>
        <van-icon name="arrow" ></van-icon>
      </a>
    </div>
    <!-- == form 表单 == -->
    <div class="login">
    <!-- ... -->
    <!-- 表单 -->
    <van-form autocomplete="off" @submit="login">
        <van-field placeholder="请输入手机号" type="tel" :rules="mobileRules" v-model="mobile" name="mobile"></van-field>
        <van-field placeholder="请输入密码" type="password" :rules="passwordRules" v-model="password" v-if="isPass">
            <template #button>
                <cp-icon :href="`login-eye-${isShowPass ? 'on':'off'}`" @click="isShowPass=!isShowPass" ></cp-icon>
            </template>
        </van-field>
        <van-field placeholder="请输入短信验证码" :type="isPass?'password':'number'" :rules="codeRules" v-model="code" v-else>
            <template #button>
                <span @click="send" :class="time>0?'active':''">{{ time>0?time:'发送验证码' }}</span>
            </template>
        </van-field>
        <div class="cp-cell">
          <van-checkbox v-model="agree">
            <span>我已同意</span>
            <a href="javascript:;">用户协议</a>
            <span>及</span>
            <a href="javascript:;">隐私条款</a>
          </van-checkbox>
        </div>
        <div class="cp-cell">
          <van-button block round type="primary" nativeType="submit">登 录</van-button>
        </div>
        <div class="cp-cell">
          <a href="javascript:;">忘记密码？</a>
        </div>
      </van-form>
     <!-- ... -->
   </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  padding-top: 46px;
  &-head {
    padding: 30px 30px 50px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  .van-form {
    padding: 0 14px;
    .cp-cell {
      height: 52px;
      padding: 14px 16px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      .van-checkbox {
        a {
          color: var(--cp-primary);
          padding: 0 5px;
        }
      }
    }
  }
}
.active{
  color:red
}
</style>